package RxJava;

public final class RxJavaPlugins {
    /**
     * 传入对象和传出对象都必须继承自Flowable
     */
    static volatile boolean lockdown;
    static volatile Function<? super Flowable, ? extends Flowable> onFlowableAssembly;

    /**
     * F 如果已经存在就返回f（f.apply会传入source，由于f的实现类去消费），不存在就返回source
     */
    public static <T> Flowable<T> onAssembly(Flowable<T> source) {
        Function<? super Flowable, ? extends Flowable> f = onFlowableAssembly;
        if (f != null) {
            return apply(f, source);
        }
        return source;
    }

    /**
     *
     */
    static <T, R> R apply(Function<T, R> f, T t) {
        try {
            return f.apply(t);
        } catch (Throwable ex) {
            throw ExceptionHelper.wrapOrThrow(ex);
        }
    }


    public static void setOnFlowableAssembly(Function<? super Flowable, ? extends Flowable> onFlowableAssembly) {
        if (lockdown) {
            throw new IllegalStateException("Plugins can't be changed anymore");
        }
        RxJavaPlugins.onFlowableAssembly = onFlowableAssembly;
    }
}
